import { createStore } from 'vuex'
import { request } from "@/utils/tool.js"

export default createStore({
	state: {
		deviceList: uni.getStorageSync("device_list") || [],
		activeDeviceId: uni.getStorageSync("active_device_id") || ""
	},
	actions: {
		async initUserDevice(ctx) {
			const resp = await request({
				url: '/shebei/usershebeilist',
				method: "GET"
			})
			const list = resp.data || []
			console.log(list, 'list');
			const { activeDeviceId } = ctx.state
			let activeId = activeDeviceId
			const hasIn = list.some(item => item.shebei_id === activeDeviceId)
			if (!hasIn) {
				const [target] = list
				if (target) {
					activeId = target.shebei_id
				} else {
					activeId = ""
				}
			}
			ctx.commit("setDeviceList", list)
			ctx.commit("setActiveDeviceId", activeId)
		},
	},
	mutations: {
		setActiveDeviceId(state, id) {
			state.activeDeviceId = id
			uni.setStorageSync("active_device_id", id)
		},
		setDeviceList(state, list) {
			state.deviceList = list
			uni.setStorageSync("device_list", list)
		}
	}
})